# utils/detection.py
import numpy as np
from utils.region_split import assign_region

def detect_anomalies(df, config):
    df["Region"] = df.apply(lambda row: assign_region(row["lat"], row["lon"]), axis=1)

    # df["IDW_residual"] = df["pre"] - df["IDW"]
    df["Kriging_residual"] = df["pre"] - df["Kriging"]
    # df["IDW_relative_error"] = df["IDW_residual"].abs() / (df["pre"] + 0.1)
    df["Kriging_relative_error"] = df["Kriging_residual"].abs() / (df["pre"] + 0.1)
    # 计算 Z_value，处理分母为 0 的情况
    df["Z_value"] = np.where(df["Kriging_std"] == 0, 0, df["Kriging_residual"] / df["Kriging_std"])
    def classify(row):
        z = abs(row["Z_value"])
        # idw_res = abs(row["IDW_residual"])
        krig_res = abs(row["Kriging_residual"])
        rel_err = row["Kriging_relative_error"]

        # 小雨特例处理
        if row["pre"] < config.SMALL_RAIN_THRESH:
            rel_err_thresh = config.SMALL_RAIN_RELATIVE_ERROR_THRESH
        else:
            rel_err_thresh = config.RELATIVE_ERROR_THRESH

        if z >= config.Z_STRONG and krig_res > config.KRIG_RES_THRESH and rel_err > rel_err_thresh:
            return "明确异常"
        # elif config.Z_WEAK <= z < config.Z_STRONG and (idw_res > config.IDW_RES_THRESH or rel_err > rel_err_thresh):
        #     return "可疑异常"
        # elif krig_res > config.KRIG_RES_THRESH and idw_res > config.IDW_RES_THRESH and z < config.Z_WEAK:
        #     return "插值不确定"
        # elif idw_res > config.IDW_RES_THRESH and krig_res < config.KRIG_RES_THRESH and z < config.Z_WEAK:
        #     return "IDW不准"
        else:
            return "正常"

    df["异常等级"] = df.apply(classify, axis=1)
    return df
